<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\adminapi\controller\v1\marketing;

use app\adminapi\controller\AuthController;
use app\services\activity\coupon\StoreCouponIssueServices;
use app\services\product\product\StoreProductCouponServices;
use app\services\product\product\StoreProductServices;
use think\facade\App;

/**
 * 已发布优惠券管理
 * Class StoreCouponIssue
 * @package app\adminapi\controller\v1\marketing
 */
class StoreCouponIssue extends AuthController
{
    public function __construct(App $app, StoreCouponIssueServices $services)
    {
        parent::__construct($app);
        $this->services = $services;
    }

    /**
     * 获取优惠券列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $where = $this->request->getMore([
            ['time_status', -2],
            ['title', '']
        ]);
        $where['coupon_title'] = $where['title'];
        switch($where['time_status']){
            case 0:
            case 1:
                $where['status'] = $where['time_status'];
                break;
            case 2:
                $where['status'] = -1;
                break;
            default:
                '';
        }
        if($where['time_status'] == -2) {
            $where['status'] = $where['time_status'];
        }
        $list = $this->services->getCouponIssueList($where);
        return app('json')->success($list);
    }

    /**
     * 添加优惠券
     * @return mixed
     */
    public function saveCoupon()
    {
        $data = $this->request->postMore([
            ['title', ''], // 标题
            ['total_count', 0], // 总数
            ['is_use_all_product', 0], // 是否适应所有商品
            ['has_use_limit', -1], // 是否存在门槛
            ['use_min_price', 0], // 允许使用的最小金额
            ['price', 0], // 优惠劵价格
            ['start_time', -1], // 优惠劵生效开始时间
            ['end_time', -1], // 优惠劵失效结束时间
            ['use_day', -1], // 领取后多少天可以使用
            ['available_type', -1], // 有效期类型(1. 时间范围, 2. 天数)
            ['has_get_limit', -1], // 领取限制(1. 有限制, 0. 不存在限制)
            ['get_max_count', 0], // 限制领取次数
            ['products', []], // 适用商品
            ['id',0]
        ]);
        $res = [
            'coupon_title' => $data['title'],
            'coupon_price' => $data['price'],
            'use_min_price' => $data['use_min_price'],
            'start_use_time' => $data['available_type'] == 1 ? $data['start_time'] : 0,
            'end_use_time' => $data['available_type'] == 1 ? $data['end_time'] : 0,
            'coupon_time' => $data['available_type'] == 2 ? $data['use_day'] : 0,
            'is_permanent' => $data['has_get_limit'] > 0 ? 0 : 1,
            'receive_type' => 1,
            'status' => 0,
            'total_count' => $data['total_count'],
            'type' => $data['is_use_all_product'] == 1 ? 0 : 2,
            'receive_limit' => $data['has_get_limit'] == 1 ? $data['get_max_count'] : 999,
            'products' => $data['products'],
            'id' => $data['id']
        ];
        $res = $this->services->saveCoupon($res);
        if ($res) return app('json')->success(100000);
    }

    /**
     * 修改优惠券状态
     * @param $id
     * @param $status
     * @return mixed
     */
    public function status($id, $status)
    {
        $this->services->update($id, ['status' => $status]);
        return app('json')->success(100001);
    }

    public function coupon_show(){
        [$ids] = $this->request->postMore([
            ['ids', []]
        ], true);
        foreach($ids as $id){
            $this->services->update($id, ['status' => 1,'start_time'=>time(),'end_time'=>time()+86400*999]);
        }
        return app('json')->success(100001);
    }

    public function coupon_unshow(){
        [$ids] = $this->request->postMore([
            ['ids', []]
        ], true);
        foreach($ids as $id){
            $this->services->update($id, ['status' => 0,'start_time'=>time(),'end_time'=>time()]);
        }
        return app('json')->success(100001);
    }

    /**
     * 获取优惠券详情
     * @param int $id
     * @return mixed
     */
    public function detail($id = 0)
    {
        if (!$id) return app('json')->fail(100100);
        $info = $this->services->getdetail($id);
//        $info = $this->services->get($id);
//        if ($info) $info = $info->toArray();
//        if ($info['product_id'] != '') {
//            $productIds = explode(',', $info['product_id']);
//            /** @var StoreProductServices $product */
//            $product = app()->make(StoreProductServices::class);
//            $productImages = $product->getColumn([['id', 'in', $productIds]], 'image', 'id');
//            foreach ($productIds as $item) {
//                $info['productInfo'][] = [
//                    'product_id' => $item,
//                    'image' => $productImages[$item]
//                ];
//            }
//        }
//        if ($info['category_id'] != '') {
//            $info['category_id'] = explode(',', $info['category_id']);
//            foreach ($info['category_id'] as &$category_id) {
//                $category_id = (int)$category_id;
//            }
//        }
        return app('json')->success($info);
    }

    /**
     * 删除
     * @param string $id
     * @return mixed
     */
    public function delete($id)
    {
        $this->services->update($id, ['is_del' => 1]);
        /** @var StoreProductCouponServices $storeProductService */
        $storeProductService = app()->make(StoreProductCouponServices::class);
        //删除商品关联这个优惠券
        $storeProductService->delete(['issue_coupon_id' => $id]);
        return app('json')->success(100002);
    }

    /**
     * 修改状态
     * @param $id
     * @return mixed
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function edit($id)
    {
        return app('json')->success($this->services->createForm($id));
    }

    /**
     * 领取记录
     * @param string $id
     * @return mixed|string
     */
    public function issue_log($id)
    {
        $list = $this->services->issueLog($id);
        return app('json')->success($list);
    }
}
